package me.luochenyxh.base.ext

import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.annotation.MainThread
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import kotlin.reflect.KClass

/**
 *@创建者：XH-hua
 *@创建时间：2021/4/25 17:28
 *@描述：带构造的创建ViewModel
 */

class ParamViewModelFactory<VM : ViewModel>(
    private val factory: () -> VM
) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T = factory() as T
}

inline fun <reified VM : ViewModel> ComponentActivity.viewModelToAc(
    noinline factory: () -> VM
): Lazy<VM> = viewModels { ParamViewModelFactory(factory) }

inline fun <reified VM : ViewModel> Fragment.viewModelToFm(
    noinline factory: () -> VM
): Lazy<VM> = viewModels { ParamViewModelFactory(factory) }

inline fun <reified VM : ViewModel> Fragment.viewModelToAc(noinline factory: () -> VM): Lazy<VM> =
    activityViewModels { ParamViewModelFactory(factory) }


@MainThread
public inline fun <reified VM : ViewModel> View.activityViewModels(
    noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM> = createViewModelLazy(VM::class, {  (context as ComponentActivity).viewModelStore }, factoryProducer)

@MainThread
public fun <VM : ViewModel> View.createViewModelLazy(
    viewModelClass: KClass<VM>,
    storeProducer: () -> ViewModelStore,
    factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM> {
    val factoryPromise = factoryProducer ?: { (context as ComponentActivity).defaultViewModelProviderFactory }
    return ViewModelLazy(viewModelClass, storeProducer, factoryPromise)
}

